package com.mysiteforme.admin.controller.question;

import com.mysiteforme.admin.annotation.SysLog;
import com.mysiteforme.admin.entity.question.ChQuestion;
import com.mysiteforme.admin.entity.question.ChQuestionVO;
import com.mysiteforme.admin.service.question.ChQuestionService;
import com.mysiteforme.admin.util.ExcelInsertUtil;
import com.mysiteforme.admin.util.RestResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/excel")
public class ExcelController {

    @Resource
    private ChQuestionService chQuestionService;

    @RequestMapping("/toImportExcel")
    @SysLog("去导入页面")
    public String toImport() {
        return "/ytzlquestion/chQuestion/excelin";
    }

    /**
     * 导入excel表格
     *
     * @return
     */
    @RequestMapping("/importExcel")
    @ResponseBody
    @SysLog("批量导入")
    public RestResponse importExcel(@RequestParam("file") MultipartFile file) {
        if (file != null) {
            try {
                List<ChQuestionVO> chQuestionVOs = ExcelInsertUtil.readExcel(file);
                boolean in = chQuestionService.insertExcel(chQuestionVOs);
                if (in) return RestResponse.success("导入成功");
                else return RestResponse.failure("系统繁忙");
            } catch (IOException e) {
                e.printStackTrace();
                return RestResponse.failure("IO异常");
            } catch (ParseException e) {
                e.printStackTrace();
                return RestResponse.failure("格式错误");
            }
        }
        return RestResponse.failure("请选择文件");

    }

    /**
     * 七牛上传回调
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/common/qiniu/upload/callback", method = RequestMethod.POST)
    public void qiNiuCallback1(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 接收七牛回调过来的内容
            String line = "";
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            // 设置返回给七牛的数据
            System.out.println(sb.toString());


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
